package com.eyeem.recyclerviewtools.sample.gestureview.adapter;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.alexvasilkov.android.commons.utils.Views;
import com.alexvasilkov.gestures.GestureController;
import com.alexvasilkov.gestures.animation.ViewPositionAnimator;
import com.alexvasilkov.gestures.commons.RecyclePagerAdapter;
import com.alexvasilkov.gestures.views.GestureImageView;
import com.eyeem.recyclerviewtools.sample.R;
import com.eyeem.recyclerviewtools.sample.data.Data;
import com.eyeem.recyclerviewtools.sample.gestureview.interface_.OnGesturePhotoListener;
import com.eyeem.recyclerviewtools.sample.gestureview.utils.GestureSettingsSetupListener;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.util.ArrayList;
import java.util.List;

public class PhotoPagerAdapter
        extends RecyclePagerAdapter<PhotoPagerAdapter.ViewHolder> {

    private static final long PROGRESS_DELAY = 300L;
    final int size;
    private final ViewPager viewPager;
    private List<Data> photos;
    private GestureSettingsSetupListener setupListener;
    private boolean activated;
    private OnGesturePhotoListener onPhotoListener;

    private OnSingleTapUpListener onSingleTapUpListener = new OnSingleTapUpListener() {
        @Override
        public void onSingleTapConfirmed(View view) {
            Log.e(PhotoPagerAdapter.class.getName(), "onGesturePhotoClick");
            Data photo = (Data) view.getTag();
            int pos = photos.indexOf(photo);
            if (onPhotoListener != null) {
                onPhotoListener.onGesturePhotoClick(pos);
            }
        }
    };

    public PhotoPagerAdapter(ViewPager viewPager) {
        this.viewPager = viewPager;
        size = viewPager.getContext().getResources().getDisplayMetrics().widthPixels;
    }

    public PhotoPagerAdapter(ViewPager viewPager, OnGesturePhotoListener onPhotoListener) {
        this.viewPager = viewPager;
        size = viewPager.getContext().getResources().getDisplayMetrics().widthPixels;
        this.onPhotoListener = onPhotoListener;
    }

    public void setPhotos(ArrayList<Data> photos) {
        this.photos = photos;
        notifyDataSetChanged();
    }

    public Data getPhoto(int pos) {
        return photos == null || pos < 0 || pos >= photos.size() ? null : photos.get(pos);
    }

    public void setSetupListener(GestureSettingsSetupListener listener) {
        setupListener = listener;
    }

    /**
     * To prevent ViewPager from holding heavy views (with bitmaps)  while it is not showing
     * we may just pretend there are no items in this adapter ("activate" = false).
     * But once we need to run opening animation we should "activate" this adapter again.<br/>
     * Adapter is not activated by default.
     */
    public void setActivated(boolean activated) {
        if (this.activated != activated) {
            this.activated = activated;
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return !activated || photos == null ? 0 : photos.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup container) {
        final ViewHolder holder = new ViewHolder(container).setImageClick(onSingleTapUpListener);
        holder.image.getController().getSettings().setFillViewport(true).setMaxZoom(3f);
        holder.image.getController().enableScrollInViewPager(viewPager);
        holder.image.getPositionAnimator().addPositionUpdateListener(
                new ViewPositionAnimator.PositionUpdateListener() {
                    @Override
                    public void onPositionUpdate(float state, boolean isLeaving) {
                        holder.progress.setVisibility(state == 1f ? View.VISIBLE : View.INVISIBLE);
                    }
                });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        if (setupListener != null) {
            setupListener.onSetupGestureView(holder.image);
        }

        // Temporary disabling touch controls
        if (!holder.gesturesDisabled) {
            holder.image.getController().getSettings().disableGestures();
            holder.gesturesDisabled = true;
        }

        holder.progress.animate().setStartDelay(PROGRESS_DELAY).alpha(1f);

        Data photo = photos.get(position);
        holder.image.setTag(photo);
        // Loading image
        Picasso.with(holder.image.getContext())
                .load(photo.photoUrl.replace("/h/100", "/h/" + size))
                .noFade()
                .placeholder(placeholder(photo.profileUrl))
                .into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        holder.image.setImageBitmap(bitmap);
                        holder.progress.animate().cancel();
                        holder.progress.animate().alpha(0f);
                        // Re-enabling touch controls
                        if (holder.gesturesDisabled) {
                            holder.image.getController().getSettings().enableGestures();
                            holder.gesturesDisabled = false;
                        }
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                        holder.progress.animate().alpha(0f);
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });
//        GlideHelper.loadFlickrFull(photo, holder.image,
//                new GlideHelper.ImageLoadingListener() {
//                    @Override
//                    public void onLoaded() {
//                        holder.progress.animate().cancel();
//                        holder.progress.animate().alpha(0f);
//                        // Re-enabling touch controls
//                        if (holder.gesturesDisabled) {
//                            holder.image.getController().getSettings().enableGestures();
//                            holder.gesturesDisabled = false;
//                        }
//                    }
//
//                    @Override
//                    public void onFailed() {
//                        holder.progress.animate().alpha(0f);
//                    }
//                });
    }

    @SuppressWarnings({"unchecked", "Range"})
    public static Drawable placeholder(String url) {
        Drawable d = new ColorDrawable(Color.GRAY);
        int alpha = (url == null) ? 73 : 64 + Math.abs(url.hashCode()) % 64;
        d.setAlpha(alpha);
        return d;
    }

    @Override
    public void onRecycleViewHolder(@NonNull ViewHolder holder) {
        super.onRecycleViewHolder(holder);

        if (holder.gesturesDisabled) {
            holder.image.getController().getSettings().enableGestures();
            holder.gesturesDisabled = false;
        }

        //Glide.clear(holder.image);

        holder.progress.animate().cancel();
        holder.progress.setAlpha(0f);

        holder.image.setImageDrawable(null);
    }

    public static GestureImageView getImage(RecyclePagerAdapter.ViewHolder holder) {
        return ((ViewHolder) holder).image;
    }

//    @Override
//    public void onClick(View view) {
//        Log.e(PhotoPagerAdapter.class.getName(), "onGesturePhotoClick");
//        Data photo = (Data) view.getTag();
//        int pos = photos.indexOf(photo);
//        if (onPhotoListener != null) {
//            onPhotoListener.onGesturePhotoClick(pos);
//        }
//    }

    static class ViewHolder extends RecyclePagerAdapter.ViewHolder {
        final GestureImageView image;
        final View progress;

        boolean gesturesDisabled;

        ViewHolder(ViewGroup parent) {
            super(Views.inflate(parent, R.layout.item_photo_full));
            image = Views.find(itemView, R.id.photo_full_image);
            progress = Views.find(itemView, R.id.photo_full_progress);
        }

        ViewHolder setImageClick(final OnSingleTapUpListener onPhotoListener) {
            image.getController().setOnGesturesListener(new GestureController.OnGestureListener() {
                @Override
                public void onDown(@NonNull MotionEvent e) {

                }

                @Override
                public void onUpOrCancel(@NonNull MotionEvent e) {

                }

                @Override
                public boolean onSingleTapUp(@NonNull MotionEvent e) {
                    return false;
                }

                @Override
                public boolean onSingleTapConfirmed(@NonNull MotionEvent e) {
                    if (onPhotoListener != null) {
                        onPhotoListener.onSingleTapConfirmed(image);
                    }
                    return true;
                }

                @Override
                public void onLongPress(@NonNull MotionEvent e) {

                }

                @Override
                public boolean onDoubleTap(@NonNull MotionEvent e) {
                    return false;
                }
            });//.setOnClickListener(clickListener);
            return this;
        }
    }

    public interface OnSingleTapUpListener {
        void onSingleTapConfirmed(View view);
    }

}
